import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import DiaryList from './DiaryList';
import DiaryReader from './DiaryReader';
import DiaryWriter from './DiaryWriter';
import DataHandler from './DataHandler';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      uiCode: 1,
      diaryList: [],
      selectIndex: 0,
      sections: []
    };
    DataHandler.getAllTheDiary().then(
      (result) => { 
        const sections = [
          {data:result, title:'2019-01'},
          {data:result, title:'2018-12'},
          {data:result, title:'2018-11'},
          {data:result, title:'2018-10'},
      ];
        this.setState({diaryList: result, sections}); 
      }
    ).catch(
      (error) => { console.log(error);  }
    );
  }

  returnPressed = () => {
    this.setState({uiCode:1});
  }

  saveDiaryAndReturn = (mood, body, title) => {
    DataHandler.saveDiaryAndReturn(mood, body, title).then(
      (result) => {this.setState({uiCode: 1, diaryList: result});}
    ).catch((error) => {console.log(error);});
  }

  writeDiary = () => {
    this.setState({uiCode : 3});
  }

  searchKeyword = (keyword) => {
    console.log(`search keyword is: ${keyword}`);
  }

  selectListItem = (ID, index) => {
    console.log(`ID: ${ID}  index: ${index}`);
    this.setState({uiCode : 2, selectIndex: index}); 
  }

  showDiaryList = () => {
    return (<DiaryList 
      diaryList={this.state.diaryList}
      sections={this.state.sections}
      selectListItem={this.selectListItem}
      searchKeyword={this.searchKeyword}
      writeDiary={this.writeDiary}
    />);
  } 

  showDiaryWriter = () => {
    return (<DiaryWriter 
      returnPressed={this.returnPressed}
      saveDiaryAndReturn={this.saveDiaryAndReturn}
    />);
  }

  showDiaryReader = () => {
    return (<DiaryReader 
      returnPressed={this.returnPressed}
      diaryList={this.state.diaryList}
      selectIndex={this.state.selectIndex}
      readingPreviousPressed={this.readingPreviousPressed}
      readingNextPressed={this.readingNextPressed}
    />);
  }

  render() {
    switch (this.state.uiCode) {
      case 1:
        return this.showDiaryList()
      case 2:
        return this.showDiaryReader()
      case 3:
        return this.showDiaryWriter()
    }
  }
}

